
//  removeAllListeners 删除所有监听
class EventEmitter {
    constructor(){
        this._events = {}
    }
    on(eventName,callback){ //订阅
        if(!this._events)this._events = {}
        // 在绑定不是newListener的时候会优先触发listener事件，并将参数传递
        if(eventName !== 'newListener'){
            this.emit('newListener',eventName)
        }
        let events = this._events[eventName]||[]
        events.push(callback)
        this._events[eventName] = events
    }
    emit(eventName,...rest){ //发布
        if(!this._events)this._events = {}
        let events = this._events[eventName]
        events && events.forEach(cb => cb.call(this,...rest));
    }
    once(eventName,callback){ //事件订阅一次
        function one(...args){
            callback(...args)
            this.off(eventName,one)
        }
        one.l = callback
        this.on(eventName,one)
    }
    off(eventName,callback){ //移除事件监听
        if(!this._events) this._events = {}
        this._events[eventName] = this._events[eventName].filter(fn=>{
            return fn!==callback && fn.l !== callback
        })
    }
    
}
class Girl extends EventEmitter {

}

let girl = new Girl();
// let pending = false
// girl.on('newListener', function (eventName) { // 当触发这个回调的时候 ，绑定的事件还未绑定成功 
//     if (!pending) { // vue的nextTick  flushSqudualerQueue 异步更新原理
//         Promise.resolve().then(() => {
//             girl.emit(eventName); // []  ['哭']  [库，吃]  ['哭'，’吃‘，’购物‘]
//             pending = false;
//         })
//         pending = true;
//      }
// });


// console.log('ok')
girl.on('我失恋了', function () { // {'我失恋了':[fn1,fn2,fn3],结婚了:[fn]}
    console.log('哭')
})
girl.on('我失恋了', function () {
    console.log('吃')
})
function shopping () {
    console.log('购物')
}
// girl.once('我失恋了',shopping )
// girl.off('我失恋了',shopping )

girl.emit('我失恋了')
girl.emit('我失恋了')


// 主要的发布订阅可就这几个方法
// once off emit on('newListener')

